<template>
	<div class="system-file-container layout-padding" style="overflow: hidden">
		<splitpanes class="default-theme" @resize="paneSize = $event[0].size">
			<pane :size="15">
				<div class="system-catalog-container">
					<div class="card-header">
						<el-input size="default" placeholder="输入分类名称自动搜索" clearable v-model="filterFileCatalogText"> </el-input>
					</div>
					<el-card shadow="hover" class="layout-padding-auto">
						<div class="file-catalog-content">
							<el-tree
								ref="FileCatalogRef"
								:allow-drop="allowDrop"
								:allow-drag="allowDrag"
								:data="stateFileCatalog.datas"
								draggable
								:default-expand-all="false"
								node-key="id"
								:props="{ label: 'catalogName' }"
								:default-expanded-keys="stateFileCatalog.expandedKeys"
								:expand-on-click-node="false"
								:filter-node-method="filterFileCatalogNode"
								@node-drag-start="handleDragStart"
								@node-drag-enter="handleDragEnter"
								@node-drag-leave="handleDragLeave"
								@node-drag-over="handleDragOver"
								@node-drag-end="handleDragEnd"
								@node-drop="handleDrop"
								@node-click="handleFileCatalogNode"
							>
								<template v-slot:default="{ node, data }">
									<div class="filecataglog-execute" @mouseover="onShow(data)" @mouseleave="onHide(data)">
										<span class="tooltip">
											<span>{{ node.label }}</span>
										</span>
										<div v-if="data.show" class="filecataglog-txt-execute">
											<el-button size="small" link type="info" @click="handleExecFileCatalogNodeData('add', data)">添加</el-button>
											<el-button v-if="data.id !== '0'" size="small" link type="info" @click="handleExecFileCatalogNodeData('edit', data)"
												>修改</el-button
											>
											<el-button v-if="data.id !== '0'" size="small" link type="info" @click="handleExecFileCatalogNodeData('delete', data)"
												>删除</el-button
											>
										</div>
									</div>
								</template>
							</el-tree>
						</div>
					</el-card>
				</div>
			</pane>
			<pane :size="85" style="overflow: hidden">
				<div class="system-file-content-container" style="overflow: hidden">
          <div class="standard-container layout-padding-no-left layout-pd" style="overflow: hidden; width: 100%;">
						<div class="review-list-title">
							<div class="title-actions">
								<el-button size="default" type="primary" class="ml10" @click="handleSearch">
									<el-icon>
										<ele-Search />
									</el-icon>
									查询
								</el-button>
								<el-button size="default" type="primary" class="ml10" @click="batchDeleteFile">
									<el-icon>
										<ele-FolderAdd />
									</el-icon>
									批量删除
								</el-button>
								<el-button size="default" type="primary" class="ml10" @click="onOpenAddFile">
									<el-icon>
										<ele-FolderAdd />
									</el-icon>
									新增文件
								</el-button>
								<!-- <el-form ref="tableSearchRef" size="default" :model="fileSearchState" label-width="100px" class="table-form">
									<el-row>
										<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
											<el-form-item label="文件名称" prop="originaleName">
												<el-input size="default" placeholder="请输入文件名称" clearable style="width: 100%" v-model="fileSearchState.originalName">
												</el-input>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="state.isToggle">
											<el-form-item label="创建时间" prop="searchDateTime">
												<el-date-picker
													type="datetimerange"
													v-model="fileSearchState.searchDateTime"
													start-placeholder="创建开始时间"
													end-placeholder="创建时间"
													style="width: 100%"
												/>
											</el-form-item>
										</el-col>

										<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" :class="{ mt10: state.isToggle }">
											<el-form-item class="table-form-btn" label-width="10px">
												<div class="table-form-btn-toggle ml10 cursor-pointer" @click="state.isToggle = !state.isToggle">
													<span>{{ state.isToggle ? '收筛选' : '展筛选' }}</span>
													<SvgIcon :name="state.isToggle ? 'ele-ArrowUp' : 'ele-ArrowDown'" />
												</div>
												<el-button size="default" type="primary" class="ml10" @click="handleSearch">
													<el-icon>
														<ele-Search />
													</el-icon>
													查询
												</el-button>
												<el-button size="default" type="primary" class="ml10" @click="batchDeleteFile">
													<el-icon>
														<ele-FolderAdd />
													</el-icon>
													批量删除
												</el-button>
												<el-button size="default" type="primary" class="ml10" @click="onOpenAddFile">
													<el-icon>
														<ele-FolderAdd />
													</el-icon>
													新增文件
												</el-button>
											</el-form-item>
										</el-col>
									</el-row>
								</el-form> -->
							</div>
						</div>
						<div class="body-container" style="overflow: hidden">
							<el-scrollbar :wrap-style="{ overflowX: 'hidden' }">
								<div class="mar10" style="width: 98%">
									<el-row :gutter="5" style="margin-left: 0px; margin-right: 0px">
										<el-col v-for="file in state.tableData.data" :xs="24" :sm="12" :md="8" :lg="4" :xl="3">
											<el-card class="file-content" :class="{ active: selected(file.id) }" @click="onHandleFileSelect(file.id)">
												<div>
													<el-image
														v-if="file.fileType == 'image'"
														:src="file.visitAbsPath"
														fit="contain"
														class="image"
														:preview-src-list="[file.visitAbsPath]"
													/>

													<el-image
														v-else
														:src="file.coverImagePath"
														fit="contain"
														class="image"
														@click.stop="onOpenAndDownloadFile(file.fileType, file.originalName, file.visitAbsPath)"
													/>
												</div>
												<!-- <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image" /> -->
												<div style="padding: 5px; height: 75px">
													<div class="bottom-content" :title="file.originalName">{{ file.originalName }}</div>
													<div class="bottom">
														<time class="time">{{ file.createTime }}</time>
														<el-button text class="button" @click.stop="deleteFile(file.id)"
															><el-icon><ele-Delete /></el-icon
														></el-button>
													</div>
												</div>
											</el-card>
										</el-col>
									</el-row>
								</div>
							</el-scrollbar>
						</div>
						<div class="pagination-container">
							<el-pagination
								:pager-count="15"
								:page-sizes="[10, 15, 20, 30, 50, 100]"
								v-model:current-page="state.tableData.paging.currentPage"
								background
								v-model:page-size="state.tableData.paging.pageSize"
								layout="total, sizes, prev, pager, next, jumper"
								:total="state.tableData.paging.totalCount"
							>
							</el-pagination>
						</div>
					</div>
				</div>
			</pane>
		</splitpanes>

		<FileCatalogDialog ref="FileCatalogDialogRef" @refreshFileCatalog="refreshFileCatalog"></FileCatalogDialog>
		<FileDialog ref="FileDialogRef" @refreshFile="refreshFile"></FileDialog>

		<VideoDialog ref="VideoDialogRef"></VideoDialog>

		<AudioDialog ref="AudioDialogRef"></AudioDialog>

		<FileChoiceDialog ref="FileChoiceDialogRef" @choiceFile="choiceFileData"></FileChoiceDialog>
	</div>
</template>

<script setup lang="ts">
import { fileApi } from '/@/api/file/index';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import { reactive, ref, defineAsyncComponent, onMounted, watch } from 'vue';
import msg from '/@/utils/messageUtils';
import { ElMessageBox, ElMessage } from 'element-plus';

const FileDialog = defineAsyncComponent(() => import('/@/views/file/dialog.vue'));

const FileCatalogDialog = defineAsyncComponent(() => import('/@/views/file/fileCatalogDialog.vue'));

const VideoDialog = defineAsyncComponent(() => import('/@/views/file/videoDialog.vue'));

const AudioDialog = defineAsyncComponent(() => import('/@/views/file/audioDialog.vue'));

const FileChoiceDialog = defineAsyncComponent(() => import('/@/views/file/choice/index.vue'));

const FileChoiceDialogRef = ref();

const FileCatalogRef = ref();
const handleFileChoice = () => {
	FileChoiceDialogRef.value.openFileChoideDialog();
};

const FileCatalogDialogRef = ref();
const FileDialogRef = ref();
const VideoDialogRef = ref();
const AudioDialogRef = ref();
const paneSize = ref(50);
const selectedFileIds = ref<Set<string>>(new Set());

const stateFileCatalog = reactive({
	datas: [],
	expandedKeys: ['0'],
	title: '新增目录',
	search: '',
});

const filterFileCatalogText = ref('');

watch(filterFileCatalogText, (val) => {
	FileCatalogRef.value!.filter(val);
});

const state = reactive({
	isToggle: false,
	tableData: {
		data: [],
		total: 0,
		loading: false,
		paging: {
			currentPage: 1,
			pageSize: 25,
			totalCount: null,
			totalPages: null,
		},
	},
});

const fileCatalogChoice = reactive({
	catalogId: '',
});

const fileSearchState = reactive({
	originalName: '',
	startSearchDateTime: null,
	endSearchDateTime: null,
	searchDateTime: [],
});

const handleSearch = () => {
	const st: any = fileSearchState.searchDateTime;
	if (st.length > 0) {
		fileSearchState.startSearchDateTime = st[0].getTime();
		fileSearchState.endSearchDateTime = st[1].getTime();
	}
	loadFileTableData();
};

const onShow = (data: any) => {
	data.show = true;
};

const onHide = (data: any) => {
	data.show = false;
};

const loadFileCatalog = async () => {
	try {
		const { data } = await fileApi().tree_catalog();
		stateFileCatalog.datas = data;
	} catch (error) {
		msg().error('获取文件分类失败');
	}
};

const loadFileTableData = async () => {
	try {
		const { data } = await fileApi().search({
			catalogId: fileCatalogChoice.catalogId,
			startSearchDateTime: fileSearchState.startSearchDateTime,
			endSearchDateTime: fileSearchState.endSearchDateTime,
			originalName: fileSearchState.originalName,
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
	} catch (error) {
		msg().error('获取文件列表失败');
	}
};

const handleSelectionFile = () => {};

watch(
	() => state.tableData.paging.currentPage,
	(newV, oldv) => {
		// console.log(`currentPage, newV: ${newV}, oldV : ${oldv}`);
		loadFileTableData();
	}
);

watch(
	() => state.tableData.paging.pageSize,
	(newV, oldv) => {
		console.log(`pageSize, newV: ${newV}, oldV : ${oldv}`);
		state.tableData.paging.pageSize = newV;
		state.tableData.paging.currentPage = 1;
		loadFileTableData();
	}
);
const onHandleSizeChange = (val: number) => {
	state.tableData.paging.pageSize = val;
	state.tableData.paging.currentPage = 1;
	loadFileTableData();
};

const onHandleCurrentChange = (val: number) => {
	loadFileTableData();
};

const onHandleFileSelect = (id: string) => {
	if (selectedFileIds.value.has(id)) {
		selectedFileIds.value.delete(id);
	} else {
		selectedFileIds.value.add(id);
	}
};
const selected = (id: any) => {
	// return true;
	return selectedFileIds.value.has(id);
};

onMounted(() => {
	loadFileCatalog();
	loadFileTableData();
});
const filterFileCatalogNode = (value: string, data: any) => {
	console.log('data: ', data);
	if (!value) return true;
	return data.catalogName.includes(value);
};

const refreshFileCatalog = (node: any) => {
	loadFileCatalog();
};

const handleExecFileCatalogNodeData = (type: string, data: any) => {
	console.log('type: ', type);
	if (type === 'delete') {
		ElMessageBox.confirm(`此操作将永久删除文件分类名称：“${data.catalogName}”，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(async () => {
				try {
					await fileApi().delete_catalog(data.id);
					msg().success('删除成功');
					loadFileCatalog();
				} catch (error) {
					msg().error('删除分类失败....');
				}
			})
			.catch(() => {});
	} else {
		if (type === 'edit') {
			FileCatalogDialogRef.value.openDialog('edit', data);
		} else {
			FileCatalogDialogRef.value.openDialog('add', data);
		}
	}
};

const handleDragStart = (node: Node) => {
	// console.log('drag start', node);
};
const handleDragEnter = (draggingNode: Node, dropNode: Node) => {
	// console.log('tree drag enter:', dropNode.label);
};
const handleDragLeave = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
	// console.log('tree drag leave:', dropNode.label);
};
const handleDragOver = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
	// console.log('tree drag over:', dropNode.label);
};
const handleDragEnd = (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {
	// console.log('tree drag end:', dropNode && dropNode.label, dropType);
};
const handleDrop = async (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {
	// console.log('tree drop:', dropNode.label, dropType);
	// console.log('handleDrop---draggingNode: ', draggingNode.data.deptName, ' , draggingNode.data.id: ', draggingNode.data.id);
	// console.log('handleDrop---dropNode: ', dropNode.data.deptName, ' , dropNode.data.id: ', dropNode.data.id);
	// console.log('type: ', dropType);
	// try {
	// 	await deptApi().changeParent({
	// 		id: draggingNode.data.id,
	// 		parentId: dropNode.data.id,
	// 	});
	// } catch (error) {
	// 	msg().error('移动部门失败,请重试');
	// }
};
const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
	// console.log('allowDrop---draggingNode: ', draggingNode.data.deptName, ' , draggingNode.data.id: ', draggingNode.data.id);
	// console.log('allowDrop---dropNode: ', dropNode.data.deptName, ' , dropNode.data.id: ', dropNode.data.id);
	// console.log('type: ', type);
	// if (dropNode.data.id === '0') {
	// 	return type !== 'next' && type !== 'prev';
	// } else {
	// 	return type === 'inner';
	// }
};

const allowDrag = (draggingNode: Node) => {
	// console.log('draggingNode: ', draggingNode.data.deptName, ' , draggingNode.data.id: ', draggingNode.data.id);
	// return draggingNode.data.id !== '0';
};

const handleFileCatalogNode = (node: any) => {
	if (fileCatalogChoice.catalogId !== node.id) {
		console.log('点击分类： ', node.id);
		fileCatalogChoice.catalogId = node.id;
		state.tableData.paging.currentPage = 1;
		loadFileTableData();
	}
};

const refreshFile = () => {
	loadFileTableData();
};

const onOpenAddFile = () => {
	if (!fileCatalogChoice.catalogId) {
		msg().warn('请先选择文件分类');
		return;
	}
	FileDialogRef.value.openDialog(fileCatalogChoice.catalogId);
};
const batchDeleteFile = () => {
	let deleteFileIds = Array.from(selectedFileIds.value);
	console.log('selectedFileIds.value： ', deleteFileIds);
	if (deleteFileIds.length < 1) {
		msg().warn('请至少选中一个需要删除的文件');
		return;
	}
	ElMessageBox.confirm(`此操作将永久删除选中的文件，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			await fileApi().batchDelete({
				ids: deleteFileIds,
			});
			msg().success('批量删除成功');
			selectedFileIds.value.clear();
			state.tableData.paging.currentPage = 1;
			loadFileTableData();
		} catch (error) {
			msg().error('批量删除失败');
		}
	});
};

const deleteFile = (id: any) => {
	console.log('删除id:  ', id);

	ElMessageBox.confirm(`此操作将永久删除文件id："${id}"，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			const { data } = await fileApi().delete(id);
			msg().success('删除成功');
			state.tableData.paging.currentPage = 1;
			loadFileTableData();
		} catch (error) {
			msg().error('文件删除失败');
		}
	});
};

const onOpenAndDownloadFile = (type: string, name: string, url: string) => {
	console.log('type: ', type);
	console.log('name: ', name);
	console.log('url: ', url);
	if (type == 'video') {
		console.log('this is video');
		VideoDialogRef.value.openVideoDialog(name, url);
	} else if (type == 'audio') {
		console.log('this is audio');
		AudioDialogRef.value.openAudioDialog(name, url);
	} else {
		window.open(url);
	}
};

const choiceFileData = (param: ChoiceFileInfo) => {
	console.log('选择图片, param: ', param);
};
</script>

<style lang="scss" scoped>
.system-file-container {
	// padding: 15px !important;
	overflow: hidden;
	height: calc(100vh - 84px);
	.system-catalog-container {
		height: 100%;
		:deep(.el-card__body) {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: auto;
			// margin: 15px 15px 40px 15px;
			// padding: 0px;
		}
		:deep(.el-tree-node__content) {
			// display: block !important;
		}
	}

	.system-file-content-container {
		height: 100%;
		:deep(.el-card__body) {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: auto;
			.el-table {
				flex: 1;
			}
		}
		.file-content {
			position: relative;
			cursor: pointer;
			margin-bottom: 10px;
			box-sizing: content-box;
			:deep(.el-card__body) {
				display: flex;
				flex-direction: column;
				flex: 1;
				overflow: auto;
				padding: 0px;
				.el-table {
					flex: 1;
				}
			}
		}

		.active {
			border: 1px solid #2b89fd;
			box-sizing: content-box;
		}

		.active::before {
			content: '';
			position: absolute;
			right: 0;
			// bottom: 0;
			top: 0;
			border: 12px solid #2b89fd;
			// border-top-color: transparent;
			border-left-color: transparent;
			border-bottom-color: transparent;
			// border-right-color: transparent;
		}
		.active::after {
			content: '';
			display: block;
			width: 5px;
			height: 10px;
			position: absolute;
			right: 4px;
			// bottom: 5px;
			top: 5px;
			// border: 1px solid #fff;
			// border-top-color: transparent;
			// border-left-color: transparent;
			// border-bottom-color: transparent;
			// border-right-color: transparent;
			// border-right-color: transparent;
			// transform: rotate(45deg);
			cursor: pointer;
		}

		.bottom-content {
			width: 100%;
			overflow: hidden;
			cursor: pointer;
			white-space: nowrap;
			text-overflow: ellipsis;

			&:hover {
				background-color: var(--next-bg-color);
			}
		}
		.bottom {
			margin-top: 10px;
			line-height: 12px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.button {
				padding: 0;
				min-height: auto;
			}
		}
		.image {
			width: 100%;
			display: block;
			height: 150px;
		}
	}
}
.system-file-search {
	display: flex;
	.table-form {
		flex: 1;
		.table-form-btn-toggle {
			white-space: nowrap;
			user-select: none;
			display: flex;
			align-items: center;
			color: var(--el-color-primary);
		}
	}
}
.splitpanes__pane {
}
.splitpanes--horizontal {
	.splitpanes__splitter {
		padding: 15px 0 0 0 !important;
	}
}

.filecataglog-execute {
	width: 100%;
}
.filecataglog-txt-execute {
	z-index: 10000ss;
	display: inline-block;
	// padding: 0px 5px;
	// margin-left: 5px;
	color: #777777;
	// 	display: inline-block;
	// 	height: 20px;
	// 	line-height: 20px;
	.dept-execute-icon {
		margin: 0px 3px;
	}

	button:nth-child(1) {
		margin-left: 15px;
	}
}

.body-container {
	flex: 1;
	overflow: hidden;
	background-color: #ffffff;
	.hide-x-scrollbar {
		:deep(.el-scrollbar__wrap) {
			overflow-x: hidden !important;
		}

		:deep(.el-scrollbar__bar.is-horizontal) {
			display: none !important;
		}
	}
}
</style>
